package com.yc.weixin.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

public class HttpsRequest {
	
	private static final Logger logger = Logger.getLogger(MenuUtil.class);
	public static final String access_tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	
	
	/**
	 * 发送https请求
	 * @param requestUrl	请求地址
	 * @param requestMethod		请求方式
	 * @param message	提交的数据
	 * @return
	 */
	public static JSONObject httpsRequest(String requestUrl,String requestMethod,String message){
		JSONObject json=null;
		try {
			//创建SSLContext对象
			TrustManager[] tm={new MyX509TrustManager()};
			SSLContext ssl=SSLContext.getInstance("SSL", "SunJSSE");
			ssl.init(null, tm, new java.security.SecureRandom());
			//从ssl对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf=ssl.getSocketFactory();
			
			URL urlGet = new URL(requestUrl);
			HttpsURLConnection http = (HttpsURLConnection) urlGet
					.openConnection();
			http.setSSLSocketFactory(ssf);
			http.setDoOutput(true);
			http.setDoInput(true);
			http.setUseCaches(false);
			http.setRequestMethod(requestMethod); // 设置请求方式
			
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			
			if(message!=null){
				OutputStream outputStream=http.getOutputStream();
				outputStream.write(message.getBytes("UTF-8"));
				outputStream.close();
			}
			//从输入流中读取返回内容
			InputStream is = http.getInputStream();
			InputStreamReader inputStreamReader=new InputStreamReader(is,"utf-8");
			BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
			String str=null;
			StringBuffer buffer=new StringBuffer();
			while((str=bufferedReader.readLine())!=null){
				buffer.append(str);
			}
			
			//释放资源
			inputStreamReader.close();
			bufferedReader.close();
			is.close();
			is=null;
			http.disconnect();
			
			json=JSONObject.fromObject(buffer.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}
	
	public static JSONObject httpRequest(String requestUrl,String requestMethod,String message){
		JSONObject json=null;
        try {  
            URL url = new URL(requestUrl);  
            HttpURLConnection http = (HttpURLConnection) url.openConnection();  
  
            http.setDoOutput(false);  
            http.setDoInput(true);  
            http.setUseCaches(false);  
  
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            
            
            http.setRequestMethod(requestMethod);  
            if(message!=null){
				OutputStream outputStream=http.getOutputStream();
				outputStream.write(message.getBytes("UTF-8"));
				outputStream.close();
			}
			//从输入流中读取返回内容
			InputStream is = http.getInputStream();
			InputStreamReader inputStreamReader=new InputStreamReader(is,"utf-8");
			BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
			String str=null;
			StringBuffer buffer=new StringBuffer();
			while((str=bufferedReader.readLine())!=null){
				buffer.append(str);
			}
			
			//释放资源
			inputStreamReader.close();
			bufferedReader.close();
			is.close();
			is=null;
			http.disconnect();
			
			json=JSONObject.fromObject(buffer.toString());
  
        } catch (Exception e) {  
            System.out.println(e.getStackTrace());  
        }  
        return json;
	}
	
	public static String getAccess_token(String appid,String appsecret){
		String access_token="";
		String requestUrl=access_tokenUrl.replace("APPID", appid).replace("APPSECRET", appsecret);
		JSONObject json=httpsRequest(requestUrl,"GET",null);
		if(json!=null){
			try {
				access_token=json.getString("access_token");
			} catch (Exception e) {
				access_token=null;
			}
		}
		return access_token;
	}
}


class MyX509TrustManager implements X509TrustManager{

	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		
	}

	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		
	}

	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
	
}
